package com.blog.sys.service;

import com.blog.sys.dao.SysUserRepository;
import com.blog.sys.entity.SysUser;
import com.blog.common.exception.ParamRepetitionExcepion;
import com.blog.common.exception.UserStateUpdateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    public boolean existsUsername(String username) {
        return sysUserRepository.existsByUsername(username);
    }

    public SysUser save(SysUser user) throws ParamRepetitionExcepion {
        if (sysUserRepository.existsByUsername(user.getUsername()))
            throw new ParamRepetitionExcepion("账号");
        return sysUserRepository.save(user);
    }

    /**
     * 锁定账户
     * @param userId
     * @return
     */
    @Transactional
    public boolean lockUser(Integer userId) throws UserStateUpdateException {
        SysUser user = sysUserRepository.findSysUserById(userId);
        if (user == null)
            throw new UserStateUpdateException("没有找到用户[" + userId + "]，锁定失败.");
        user.lock();
        sysUserRepository.saveAndFlush(user);

        return true;
    }

}
